﻿using System;
using System.Collections.Generic;
using HtmlAgilityPack;
using System.Drawing;
using System.Net;
using System.IO;

namespace AMDb
{
    /// <summary>
    /// Search interface.
    /// </summary>
    internal class ISearch
    {
        public HtmlDocument doc = new HtmlDocument();
        public HtmlWeb web = new HtmlWeb();
        public string imdb = "http://imdb.com";
        public string find = "http://imdb.com/find?s=tt&ttype=ft&q=";

        public string TrimN(string input)
        {
            return input.Replace("\n", " ").Trim();
        }
        public string TrimB(string input)
        {
            return input.Replace("(", "").Replace(")","").Trim();
        }
        public Image URLtoImage(string url)
        {
            using (WebClient wc = new WebClient())
            {
                byte[] bytes = wc.DownloadData(url);
                MemoryStream ms = new MemoryStream(bytes);
                return Image.FromStream(ms);
            }
        }
    }

    /// <summary>
    /// A class that represent the information of a search result.
    /// </summary>
    public class Result
    {
        private ISearch s = new ISearch();
        internal string ImgUrl { get; set; }
        /// <summary>
        /// Get the poster icon of the movie.
        /// </summary>
        public Image PosterIcon { get { return s.URLtoImage(ImgUrl); } }
        /// <summary>
        /// Get the title of the movie.
        /// </summary>
        public string Title { get; internal set; }
        /// <summary>
        /// Get the IMDb url of the movie.
        /// </summary>
        public string Url { get; internal set; }
    }
    
    /// <summary>
    /// A class that gets the result of a search.
    /// </summary>
    public class SearchResult
    {
        private List<Result> lr;
        private ISearch s = new ISearch();
        /// <summary>
        /// Get or set the keyword to be searched.
        /// </summary>
        public string Keyword;

        /// <summary>
        /// Initialize a new instance of the AMDb.IMDb.SearchResult class to a specified keyword.
        /// </summary>
        /// <param name="Keyword">Keyword to be searched.</param>
        public SearchResult(string Keyword)
        {
            this.Keyword = Keyword;
        }
       
        /// <summary>
        /// 
        /// </summary>
        public SearchResult() { }

        /// <summary>
        /// Get search results.
        /// </summary>
        /// <returns>List of Result class</returns>
        public List<Result> getSearchResult()
        {
            Result r;
            lr = new List<Result>();
            s.doc = s.web.Load(s.find+Keyword.Replace(" ", "+"));
            foreach (HtmlNode tr in s.doc.DocumentNode.SelectNodes("//table[@class='findList']/tr"))
            {
                HtmlNodeCollection td = tr.SelectNodes(".//td");
                r = new Result();
                r.ImgUrl = td[0].SelectSingleNode("./a/img").Attributes["src"].Value;
                r.Title = s.TrimN(td[1].InnerText);
                r.Url = s.imdb + System.Text.RegularExpressions.Regex.Match(
                    td[1].SelectSingleNode("./a").Attributes["href"].Value, @".*(?=\?)").Value;
                lr.Add(r);
            }

            return lr;
        }

        /// <summary>
        /// Get search result of a movie by title.
        /// </summary>
        /// <param name="Title">Title of the movie.</param>
        /// <param name="ResultList">List of search results.</param>
        /// <returns>Result class</returns>
        public Result getMovieByTitle(string Title, List<Result> ResultList)
        {
            foreach (Result r in ResultList)
            {
                if (s.TrimB(r.Title) == s.TrimB(Title))
                    return r;
            }
            return null;
        }
        /// <summary>
        /// Get search result of a movie by IMDb id.
        /// </summary>
        /// <param name="ID">IMDb id of the movie (e.g. tt1300854).</param>
        /// <param name="ResultList">List of search results.</param>
        /// <returns>Result class</returns>
        public Result getMovieByID(string ID, List<Result> ResultList)
        {
            foreach (Result r in ResultList)
            {
                if (r.Url.Contains(ID))
                    return r;
            }
            return null;
        }
    }
}
